﻿package com.findMoneyGame.models {
	import com.findMoneyGame.server.ServerFacadeFactory;
	import com.findMoneyGame.models.UserData;
	import com.findMoneyGame.events.UserEvent;

	import flash.events.Event;

	public class User extends UserData {
		private static var _inst : User;

		private var server = ServerFacadeFactory.NewInst;


		public function get bytesTotal () : int { return server.bytesTotal; }
		
		public function get bytesLoaded () : int { return server.bytesLoaded; }


		public static function getInst () {
			if (_inst == null)
				_inst = new User(new Blocker());
			return _inst;
		}

		public function User (b : Blocker) { addEventListener(Model.UPDATE, update); }

		public function beginCheckExists () {
			server.beginCheckUserExists(
				id,
				function (data : Boolean) {
					exists = data;
					dispatchStrEvent(UserEvent.CHECK_EXISTS_COMPLETE);
				},
				function (e : Event) { dispatchStrEvent(UserEvent.CHECK_EXISTS_ERROR); }
			);
		}
		public function beginCreateNew () {
			server.beginCreateNewUser(
				id,
				function () { dispatchStrEvent(UserEvent.CREATE_NEW_COMPLETE); },
				function (e : Event) { dispatchStrEvent(UserEvent.CREATE_NEW_ERROR); }
			);
		}
		public function fetchData () {
			var dataFetched = function (userData : *) {
				_level = userData.level;
				_fastCompletedLevelCount = userData.fastCompletedLevelCount;
				_achievement = userData.achievement;

				_moneyCount = userData.moneyCount;
				_moneyBought = userData.moneyBought;
				_moneySpent = userData.moneySpent;

				_timeBonusIndex = userData.timeBonusIndex;
				_loupeBonusIndex = userData.loupeBonusIndex;
				_hintBonusIndex = userData.hintBonusIndex;

				dispatchStrEvent(UserEvent.FETCH_DATA_COMPLETE);
			};
			var dataFetchingError = function () { dispatchStrEvent(UserEvent.FETCH_DATA_ERROR); };
			server.beginFetchUserData(id, dataFetched, dataFetchingError);
		}

		private function update (e : Event) {
			var dataSaved = function () { dispatchDataSaved(); }
			var dataSavingError = function () { dispatchDataSavingError(); }
			var s = ServerFacadeFactory.NewInst;
			s.beginSaveUserData(this, dataSaved, dataSavingError);
		}
	}
}
class Blocker { public function Blocker() { } }